package com.xjscrm.console.service.customer.group.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.consertoserver.MicaGroupAddTagMsg;
import com.uzai.mobile.collect.api.enums.MicaMsgType;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.WwGroupTags;
import com.xjscrm.common.entity.WwGroupTagsRelation;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.console.mapper.WwGroupTagMapper;
import com.xjscrm.console.mapper.WwGroupTagsRelationMapper;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.group.*;
import com.xjscrm.console.service.customer.group.WwGroupTagService;
import com.xjscrm.console.vo.WwGroupTagsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WwGroupTagServiceImpl implements WwGroupTagService {

    @Autowired
    private WwGroupTagMapper wwGroupTagMapper;

    @Autowired
    private WwGroupTagsRelationMapper wwGroupTagsRelationMapper;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWwGroupTagGroup(AddWwGroupTagGroupDto addWwGroupTagGroupDto) {
        if(addWwGroupTagGroupDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(addWwGroupTagGroupDto.getFirstLevelTagName()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        //添加标签组
        int time = DateUtil.getTime();
        long id = IdWorker.getId();
        WwGroupTags wwGroupTags = new WwGroupTags();
        wwGroupTags.setMerId(addWwGroupTagGroupDto.getMerId());
        wwGroupTags.setPid(0L);
        wwGroupTags.setName(addWwGroupTagGroupDto.getFirstLevelTagName());
        wwGroupTags.setId(id);
        wwGroupTags.setCreateTime(time);
        wwGroupTags.setUpdateTime(time);
        wwGroupTagMapper.insertWwGroupTags(wwGroupTags);

        //添加标签
        if(addWwGroupTagGroupDto.getTagNames()!=null&&!addWwGroupTagGroupDto.getTagNames().isEmpty()){
            for (String tagName:addWwGroupTagGroupDto.getTagNames()) {
                long tagId = IdWorker.getId();
                WwGroupTags tags = new WwGroupTags();
                tags.setMerId(addWwGroupTagGroupDto.getMerId());
                tags.setPid(id);
                tags.setName(tagName);
                tags.setId(IdWorker.getId());
                tags.setCreateTime(time);
                tags.setUpdateTime(time);
                wwGroupTagMapper.insertWwGroupTags(tags);
            }
        }

    }

    @Override
    public void addWwGroupTag(WwGroupTagDto wwGroupTagDto) {
        if(wwGroupTagDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(StringUtils.isBlank(wwGroupTagDto.getTagName())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(wwGroupTagDto.getPid()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        WwGroupTagQuery wwGroupTagQuery=new WwGroupTagQuery();
        wwGroupTagQuery.setMerId(wwGroupTagDto.getMerId());
        wwGroupTagQuery.setTagName(wwGroupTagDto.getTagName());
        List<WwGroupTagsVo> wwGroupTagsVoList= wwGroupTagMapper.getWwGroupTag(wwGroupTagQuery);
        if(wwGroupTagsVoList!=null&&!wwGroupTagsVoList.isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "重复的标签名");
        }

        int time = DateUtil.getTime();
        WwGroupTags tags = new WwGroupTags();
        tags.setMerId(wwGroupTagDto.getMerId());
        tags.setPid(wwGroupTagDto.getPid());
        tags.setName(wwGroupTagDto.getTagName());
        tags.setId(IdWorker.getId());
        tags.setCreateTime(time);
        tags.setUpdateTime(time);
        wwGroupTagMapper.insertWwGroupTags(tags);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleWwGroupTag(WwGroupTagDto wwGroupTagDto) {
        if(wwGroupTagDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(wwGroupTagDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwGroupTags wwGroupTags = wwGroupTagMapper.getById(wwGroupTagDto.getId(), wwGroupTagDto.getMerId());
        if(wwGroupTags!=null){

            if (wwGroupTags.getPid() != null && wwGroupTags.getPid() == 0) {
                WwGroupTagQuery wwGroupTagQuery = new WwGroupTagQuery();
                wwGroupTagQuery.setPid(wwGroupTags.getId());
                wwGroupTagQuery.setMerId(wwGroupTags.getMerId());
                List<WwGroupTagsVo> wwGroupTagsVoList = wwGroupTagMapper.getWwGroupTag(wwGroupTagQuery);
                if (wwGroupTagsVoList != null && !wwGroupTagsVoList.isEmpty()) {
                    for (WwGroupTagsVo wwGroupTagsVo : wwGroupTagsVoList) {
                        //删除标签
                        wwGroupTagMapper.deleById(wwGroupTagsVo.getId(), wwGroupTagsVo.getMerId());

                        //删除标签和客户群关系
                        WwGroupTagsRelationQuery wwGroupTagsRelationQuery = new WwGroupTagsRelationQuery();
                        wwGroupTagsRelationQuery.setMerId(wwGroupTagsVo.getMerId());
                        wwGroupTagsRelationQuery.setTagId(wwGroupTagsVo.getId());
                        List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
                        if (wwGroupTagsRelationList != null && !wwGroupTagsRelationList.isEmpty()) {
                            for (WwGroupTagsRelation wwGroupTagsRelation : wwGroupTagsRelationList) {
                                wwGroupTagsRelationMapper.deleById(wwGroupTagsRelation.getId(), wwGroupTagsRelation.getMerId());
                            }
                        }
                    }
                }

            }


            //删除标签
            wwGroupTagMapper.deleById(wwGroupTags.getId(),wwGroupTags.getMerId());

            //删除标签和客户群关系
            WwGroupTagsRelationQuery wwGroupTagsRelationQuery=new WwGroupTagsRelationQuery();
            wwGroupTagsRelationQuery.setMerId(wwGroupTags.getMerId());
            wwGroupTagsRelationQuery.setTagId(wwGroupTags.getId());
            List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
            if(wwGroupTagsRelationList!=null&&!wwGroupTagsRelationList.isEmpty()){
                for (WwGroupTagsRelation wwGroupTagsRelation:wwGroupTagsRelationList) {
                    wwGroupTagsRelationMapper.deleById(wwGroupTagsRelation.getId(),wwGroupTagsRelation.getMerId());
                }
            }
        }

    }

    @Override
    public void updateWwGroupTag(WwGroupTagDto wwGroupTagDto) {
        if(wwGroupTagDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(wwGroupTagDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if(StringUtils.isBlank(wwGroupTagDto.getTagName())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        WwGroupTags wwGroupTags = wwGroupTagMapper.getById(wwGroupTagDto.getId(), wwGroupTagDto.getMerId());
        if(wwGroupTags!=null){
            wwGroupTags.setName(wwGroupTagDto.getTagName());
            wwGroupTags.setGroupKeword(JSONObject.toJSONString(wwGroupTagDto.getGroupKeword()));
            wwGroupTags.setUpperLimit(wwGroupTagDto.getUpperLimit());
            wwGroupTags.setGroupKeyWordSwitch(wwGroupTagDto.getGroupKeyWordSwitch());
            wwGroupTags.setUpperLimitSwitch(wwGroupTagDto.getUpperLimitSwitch());
            wwGroupTagMapper.updateWwGroupTags(wwGroupTags);
        }
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void AddWwGroupTagRel(WwGroupTagRelDto wwGroupTagRelDto) {
        if(wwGroupTagRelDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(StringUtils.isBlank(wwGroupTagRelDto.getGroupWxid())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(StringUtils.isBlank(wwGroupTagRelDto.getDeviceId())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(wwGroupTagRelDto.getTagIds()==null||wwGroupTagRelDto.getTagIds().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }


        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        Boolean transactionSuccess = transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                try {
                    for (Long tagId : wwGroupTagRelDto.getTagIds()) {
                        WwGroupTagsRelation wwGroupTagsRelation = new WwGroupTagsRelation();
                        wwGroupTagsRelation.setGroupWxid(wwGroupTagRelDto.getGroupWxid());
                        wwGroupTagsRelation.setMerId(wwGroupTagRelDto.getMerId());
                        wwGroupTagsRelation.setDeviceId(wwGroupTagRelDto.getDeviceId());
                        wwGroupTagsRelation.setTagId(tagId);
                        wwGroupTagsRelationMapper.addWwGroupTagsRelation(wwGroupTagsRelation);
                    }
                    return true; // Transaction successful
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return false; // Transaction failed
                }
            }
        });


        //执行成功后 发送mq指令
        if (transactionSuccess) {
            for (Long tagId : wwGroupTagRelDto.getTagIds()) {
                MicaGroupAddTagMsg micaCustomerAddTagMsg = new MicaGroupAddTagMsg();
                micaCustomerAddTagMsg.setTagId(tagId);
                micaCustomerAddTagMsg.setGroupWxid(wwGroupTagRelDto.getGroupWxid());
                MicaTransDto micaTransDto = MicaTransDto.newInstance(micaCustomerAddTagMsg, MicaMsgType.CONSOLE_TO_SERVER_GROUP_ADD_TAG);
                micaTransDto.setMerId(wwGroupTagRelDto.getMerId());
                micaTransDto.setDeviceId(wwGroupTagRelDto.getDeviceId());
                micaTransDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
                sendMsgProducer.pushMsg(micaTransDto, MicaTopics.CONSOLE_TO_SERVER_TOPIC);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleWwGroupTagRel(WwGroupTagRelDto wwGroupTagRelDto) {
        if(wwGroupTagRelDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(StringUtils.isBlank(wwGroupTagRelDto.getGroupWxid())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(StringUtils.isBlank(wwGroupTagRelDto.getDeviceId())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(wwGroupTagRelDto.getTagIds()==null||wwGroupTagRelDto.getTagIds().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        for (Long tagId:wwGroupTagRelDto.getTagIds()) {
            WwGroupTagsRelationQuery wwGroupTagsRelationQuery=new WwGroupTagsRelationQuery();
            wwGroupTagsRelationQuery.setGroupWxid(wwGroupTagRelDto.getGroupWxid());
            wwGroupTagsRelationQuery.setMerId(wwGroupTagRelDto.getMerId());
            wwGroupTagsRelationQuery.setDeviceId(wwGroupTagRelDto.getDeviceId());
            wwGroupTagsRelationQuery.setTagId(tagId);
            List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
            if(wwGroupTagsRelationList!=null&&!wwGroupTagsRelationList.isEmpty()){
                wwGroupTagsRelationList.forEach(it->wwGroupTagsRelationMapper.deleById(it.getId(),it.getMerId()));
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void moveWwGroupTagRel(WwGroupTagRelDto wwGroupTagRelDto) {
        if(wwGroupTagRelDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(StringUtils.isBlank(wwGroupTagRelDto.getGroupWxid())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(StringUtils.isBlank(wwGroupTagRelDto.getDeviceId())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if(wwGroupTagRelDto.getTagIds()==null||wwGroupTagRelDto.getTagIds().isEmpty()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }


        //先删除已有的客户群和群标签关系
        WwGroupTagsRelationQuery wwGroupTagsRelationQuery=new WwGroupTagsRelationQuery();
        wwGroupTagsRelationQuery.setGroupWxid(wwGroupTagRelDto.getGroupWxid());
        wwGroupTagsRelationQuery.setMerId(wwGroupTagRelDto.getMerId());
        wwGroupTagsRelationQuery.setDeviceId(wwGroupTagRelDto.getDeviceId());
        List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.getWwGroupTagsRelationList(wwGroupTagsRelationQuery);
        if(wwGroupTagsRelationList!=null&&!wwGroupTagsRelationList.isEmpty()){
            wwGroupTagsRelationList.forEach(it->wwGroupTagsRelationMapper.deleById(it.getId(),it.getMerId()));
        }

        //再进行添加
        for (Long tagId:wwGroupTagRelDto.getTagIds()) {
            WwGroupTagsRelation wwGroupTagsRelation=new WwGroupTagsRelation();
            wwGroupTagsRelation.setGroupWxid(wwGroupTagRelDto.getGroupWxid());
            wwGroupTagsRelation.setMerId(wwGroupTagRelDto.getMerId());
            wwGroupTagsRelation.setDeviceId(wwGroupTagRelDto.getDeviceId());
            wwGroupTagsRelation.setTagId(tagId);
            wwGroupTagsRelationMapper.addWwGroupTagsRelation(wwGroupTagsRelation);
        }
    }


    @Override
    public Object getWwGroupTagTree(BaseDto baseDto) {
        if(baseDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        WwGroupTagQuery wwGroupTagQuery=new WwGroupTagQuery();
        wwGroupTagQuery.setMerId(baseDto.getMerId());
        List<WwGroupTagsVo> wwGroupTagsVoList = wwGroupTagMapper.getWwGroupTag(wwGroupTagQuery);
        if(wwGroupTagsVoList==null||wwGroupTagsVoList.isEmpty()){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"标签不存在");
            return null;
        }
         ArrayList<Map> arrayList = new ArrayList<>();
        for (WwGroupTagsVo wwGroupTagsVo:wwGroupTagsVoList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",wwGroupTagsVo.getId());
            map.put("tagName",wwGroupTagsVo.getName());
            map.put("pid",wwGroupTagsVo.getPid());
            arrayList.add(map);
        }
        return arrayList;
    }

    @Override
    public Object getWwGroupTagDetail(WwGroupTagDto wwGroupTagDto) {
        if(wwGroupTagDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(wwGroupTagDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwGroupTags wwGroupTags = wwGroupTagMapper.getById(wwGroupTagDto.getId(), wwGroupTagDto.getMerId());
        WwGroupTagsVo wwGroupTagsVo = new WwGroupTagsVo();
        BeanUtil.copyProperties(wwGroupTags,wwGroupTagsVo);
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            if(wwGroupTags.getGroupKeword()!=null){
                wwGroupTagsVo.setGroupKeword(objectMapper.readValue(wwGroupTags.getGroupKeword(),List.class));
            }

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return wwGroupTagsVo;
    }
}
